package com.baize.baizeapp.test.jetpack2.repository

import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.liveData
import com.baize.baizeapp.test.jetpack2.DataService
import com.baize.baizeapp.test.jetpack2.http.Resource
import com.baize.baizeapp.test.jetpack2.repository.bean.HospitalInfoResp
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.async
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

class HospitalRepository {

    fun fetchHospitalInfo(orderId: Long): LiveData<Resource<HospitalInfoResp>> {
        return liveData(Dispatchers.IO) {
            try {
                emit(Resource.loading(null))
                val retrofit = Retrofit.Builder()
                    .baseUrl("https://apihospital.ipalmap.com/hospital/screen/hospital")
                    .addConverterFactory(GsonConverterFactory.create())
                    .build()
                val service = retrofit.create(DataService::class.java)
//                val build = GetPayMethodReq.newBuilder().setOrderId(orderId).build()
                val repo = GlobalScope.async(Dispatchers.IO){
                    service.requestQuickItem("09K302","hp")
//                    CashDeskGrpc.newBlockingStub(GrpcHelper.channel).getPaymentMethods(build)
                }.await()
//                val repo = asyncIO {
//                    CashDeskGrpc.newBlockingStub(GrpcHelper.channel).getPaymentMethods(build)
//                }.await()
                if (repo != null && repo.code == 200) {
                    emit(Resource.success(repo))
                } else {
                    emit(Resource.error(Throwable(repo?.message), null))
                }
            } catch (e: Exception) {
                Log.i("yanze", "fetchHospitalInfo: ${e.message}")
                emit(Resource.error(e, null))
            }
        }
    }

}